package com.example.bob.usingservice;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements View.OnClickListener, ServiceConnection {

    private Button btnStart, btnStop, btnBind, btnUnBind,btnGetNum;
    private Intent serviceIntent;
    private EchoService echoService = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        serviceIntent = new Intent(this, EchoService.class);

        btnStart = (Button) findViewById(R.id.btnStart);
        btnStop = (Button) findViewById(R.id.btnStop);
        btnBind = (Button) findViewById(R.id.btnBind);
        btnUnBind = (Button) findViewById(R.id.btnUnBind);
        btnGetNum = (Button) findViewById(R.id.btnGetNum);

        btnStart.setOnClickListener(this);
        btnStop.setOnClickListener(this);
        btnBind.setOnClickListener(this);
        btnUnBind.setOnClickListener(this);
        btnGetNum.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnStart:
                startService(serviceIntent);
                break;
            case R.id.btnStop:
                stopService(serviceIntent);
                echoService = null;
                break;
            case R.id.btnBind:
                bindService(serviceIntent, this, Context.BIND_AUTO_CREATE);
                break;
            case R.id.btnUnBind:
                unbindService(this);
                echoService = null;
                break;
            case R.id.btnGetNum:
                if(echoService!=null){
                    System.out.println("Num is :"+echoService.getCurrentNum());
                }
                break;
        }
    }

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        System.out.println("onServiceConnected");

        echoService = ((EchoService.EchoServiceBinder)iBinder).getService();

    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {

    }
}
